/*
 * 全局权限检测
 * 包括1、路由的全局守卫
 */
import router from './router'
import { getToken, getUser, getPermissions } from '@/common/auth'
import store from './store'
import { PERMISSION_ROUTE_MAP } from './config/config'

// 路由全局前置守卫
const whiteList = ['/login'] // 白名单
router.beforeEach((to, from, next) => {
  if (to.path === '/login') {
    next()
  } else {
    if (getToken()) {
      let userState = store.state.user
      if (!userState.user.id) {
        store.commit('SET_USER', getUser())
      }
      let permissions = userState.user.permissions
      if(permissions.length === 0) {
        alert('该用户被分配角色，或角色没有任何权限！')
        window.location.reload()
        return
      }
      let toPathValid = false
      let toPath = to.path
      permissions.forEach(p => {
        let permissionId = p.permissionId
        let permissionUrl = PERMISSION_ROUTE_MAP[permissionId]
        if (toPath.indexOf(permissionUrl) !== -1) {
          toPathValid = true
        }
      })
      if (toPathValid) next()
      else next(PERMISSION_ROUTE_MAP[permissions[0].permissionId])
    } else {
      next('/login')
    }
  }
  // if (getToken()) {
  //   let user = getUser()
  //   store.commit('SET_USER', user)
  //   // 获取用户权限
  //   let permissions = []
  //   if (!store.state.user.permissions) {
  //     permissions = getPermissions()
  //   } else {
  //     // permissions = store.state.user.permissions
  //   }
  //   store.commit('SET_PERMISSIONS', permissions)
  //   let toPath = PERMISSION_ROUTE_MAP[permissions[0].permissionId]
  //   console.log(`to Path ${toPath}`)
  //   next(toPath)
  //   // // 有token访问login页面，就跳到首页
  //   // if (to.path === '/login') {
  //   //   next('/order_manage')
  //   // } else {
  //   //   next()
  //   // }
  // } else {
  //   if (whiteList.includes(to.path)) {
  //     // 白名单，免密登录
  //     next()
  //   } else {
  //     // 否则就跳动登录页面
  //     next('/login')
  //   }
  // }
})
